package com.ctshk.rpc.certificate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.certificate.dto.AppointmentHkMacauBridgeDTO;
import com.ctshk.rpc.certificate.dto.CertificateAcceptDTO;
import com.ctshk.rpc.certificate.dto.CertificateHkMacauBridgeDTO;
import com.ctshk.rpc.certificate.entity.CertificateHkMacauBridge;
import com.ctshk.rpc.certificate.mapper.CertificateBusinessMapper;
import com.ctshk.rpc.certificate.mapper.CertificateHkMacauBridgeMapper;
import com.ctshk.rpc.certificate.req.CertificateAcceptPageReq;
import com.ctshk.rpc.certificate.req.CertificateHkMacauBridgeReq;
import com.ctshk.rpc.certificate.req.ProcCommonCertificateReq;
import com.ctshk.rpc.certificate.req.QueryHkMacauBridgeReq;
import com.ctshk.rpc.certificate.service.ICertificateHkMacauBridgeService;
import com.ctshk.rpc.certificate.utils.OrderUtil;
import com.ctshk.rpc.system.service.IValidateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 粤港经港珠澳大桥口口岸入出内地商务车辆牌证业务 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-03-25
 */
@DubboService
public class CertificateHkMacauBridgeServiceImpl extends ServiceImpl<CertificateHkMacauBridgeMapper, CertificateHkMacauBridge> implements ICertificateHkMacauBridgeService {

    @Autowired
    private CertificateHkMacauBridgeMapper hkMacauBridgeMapper;

    @Autowired
    private CertificateBusinessMapper businessMapper;

    @DubboReference
    private IValidateService validateService;
    @Override
    public Result saveHkMacauBridge(CertificateHkMacauBridgeReq certificateHkMacauBridgeReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (certificateHkMacauBridgeReq == null) {
            return Result.failed(SystemError.SYS_416);
        }

        // 有id保存
        CertificateHkMacauBridge certificateHkMacauBridge;
        if (null != certificateHkMacauBridgeReq.getId()) {
            certificateHkMacauBridge = hkMacauBridgeMapper.selectById(certificateHkMacauBridgeReq.getId());
            if (Objects.isNull(certificateHkMacauBridge)) {
                return Result.failed(SystemError.SYS_411);
            }
            BeanUtils.copyProperties(certificateHkMacauBridgeReq, certificateHkMacauBridge);
            certificateHkMacauBridge.setModifiedId(userId);
            certificateHkMacauBridge.setGmtModified(LocalDateTime.now());
            hkMacauBridgeMapper.updateById(certificateHkMacauBridge);
        } else {
            // 保存预约单据
            certificateHkMacauBridge = new CertificateHkMacauBridge();
            BeanUtils.copyProperties(certificateHkMacauBridgeReq, certificateHkMacauBridge);
            Long permitId = SnowflakeIdWorker.nextId();
            certificateHkMacauBridge.setId(permitId);
            String registerNumber = OrderUtil.getReentryPermitRegisterNumber();
            certificateHkMacauBridge.setRegisterNumber(registerNumber);
            certificateHkMacauBridge.setCreateId(userId);
            certificateHkMacauBridge.setGmtCreate(LocalDateTime.now());
            certificateHkMacauBridge.setAcceptStatus(1);
            certificateHkMacauBridge.setIsDeleted(0);
            hkMacauBridgeMapper.insert(certificateHkMacauBridge);
        }

        // 预约办证中心
        if (certificateHkMacauBridgeReq.getSubmissionStatus() == 1) {
            Long res = businessMapper.reserveReentryPermit(certificateHkMacauBridgeReq.getName(), certificateHkMacauBridgeReq.getBusinessHallId(),
                    certificateHkMacauBridgeReq.getReserveDate(), certificateHkMacauBridgeReq.getReserveTime());
            if (res != 1) {
                return Result.failed(new BusinessException(SystemError.CERTIFICATE_BUSINESS_16002));
            }
        }
        return Result.success(certificateHkMacauBridge.getId());
    }

    @Override
    public CertificateHkMacauBridgeDTO queryDetail(Long id) {
        CertificateHkMacauBridge certificateHkMacauBridge = hkMacauBridgeMapper.selectById(id);
        if (Objects.isNull(certificateHkMacauBridge)) {
            throw new BusinessException(SystemError.SYS_411);
        }
        CertificateHkMacauBridgeDTO hkMacauBridgeDTO = new CertificateHkMacauBridgeDTO();
        BeanUtils.copyProperties(certificateHkMacauBridge, hkMacauBridgeDTO);
        return hkMacauBridgeDTO;
    }

    @Override
    public Result updateHkMacauBridge(CertificateHkMacauBridgeReq certificateHkMacauBridgeReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (certificateHkMacauBridgeReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        CertificateHkMacauBridge certificateHkMacauBridge = hkMacauBridgeMapper.selectById(certificateHkMacauBridgeReq.getId());
        if (Objects.isNull(certificateHkMacauBridge)) {
            return Result.failed(SystemError.SYS_411);
        }
        BeanUtils.copyProperties(certificateHkMacauBridgeReq, certificateHkMacauBridge);
        certificateHkMacauBridge.setModifiedId(userId);
        certificateHkMacauBridge.setGmtModified(LocalDateTime.now());
        hkMacauBridgeMapper.updateById(certificateHkMacauBridge);
        return Result.success();
    }

    @Override
    public Result procReserveHkMacauBridge(ProcCommonCertificateReq procReserveHkMacauBridgeReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (procReserveHkMacauBridgeReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        CertificateHkMacauBridge certificateHkMacauBridge = hkMacauBridgeMapper.selectById(procReserveHkMacauBridgeReq.getId());
        if (Objects.isNull(certificateHkMacauBridge)) {
            return Result.failed(SystemError.SYS_411);
        }
        certificateHkMacauBridge.setAcceptStatus(procReserveHkMacauBridgeReq.getAcceptStatus());
        certificateHkMacauBridge.setModifiedId(userId);
        certificateHkMacauBridge.setGmtModified(LocalDateTime.now());
        certificateHkMacauBridge.setAcceptDesc(procReserveHkMacauBridgeReq.getAcceptDesc());
        hkMacauBridgeMapper.updateById(certificateHkMacauBridge);
        return Result.success();
    }

    @Override
    public PageResponse<CertificateAcceptDTO> queryCertificateAcceptList(CertificateAcceptPageReq req) {
        Page<CertificateHkMacauBridge> certificatePage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<CertificateHkMacauBridge> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(null != req.getApplyTypeId(), CertificateHkMacauBridge::getApplyTypeId, req.getApplyTypeId());
        queryWrapper.lambda().eq(null != req.getAcceptStatus(), CertificateHkMacauBridge::getAcceptStatus, req.getAcceptStatus());

        // 处理时间区间不包括右边界问题
        if (null != req.getGmtCreateEnd()) {
            req.setGmtCreateEnd(req.getGmtCreateEnd().plusDays(1));
        }
        queryWrapper.lambda().between((null != req.getGmtCreateBegin() && null != req.getGmtCreateEnd()), CertificateHkMacauBridge::getGmtCreate, req.getGmtCreateBegin(), req.getGmtCreateEnd());
        Page<CertificateHkMacauBridge> iPage = hkMacauBridgeMapper.selectPage(certificatePage, queryWrapper);
        List<CertificateHkMacauBridge> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        List<CertificateAcceptDTO> certificateAcceptQueryDTOList = EntityUtil.copyList(records, CertificateAcceptDTO.class);
        certificateAcceptQueryDTOList.forEach(record -> {
            record.setCnName("-");
            record.setHkMacauPhone("-");
            record.setEmail("-");
        });
        return new PageResponse<>(certificateAcceptQueryDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public Result<AppointmentHkMacauBridgeDTO> queryAppointmentInfo(QueryHkMacauBridgeReq queryAppointmentInfoReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        validateService.check(queryAppointmentInfoReq.getKey(), queryAppointmentInfoReq.getCode());
        CertificateHkMacauBridge hkMacauBridge = hkMacauBridgeMapper.selectOne(new QueryWrapper<CertificateHkMacauBridge>().lambda()
                .eq(null != queryAppointmentInfoReq.getId(), CertificateHkMacauBridge::getId, queryAppointmentInfoReq.getId())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getCertificateNo()), CertificateHkMacauBridge::getCertificateNo,queryAppointmentInfoReq.getCertificateNo())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getPlateNumber()), CertificateHkMacauBridge::getRegisterNumber,queryAppointmentInfoReq.getPlateNumber()));

        AppointmentHkMacauBridgeDTO appointmentInfoDTO = new AppointmentHkMacauBridgeDTO();
        BeanUtils.copyProperties(hkMacauBridge, appointmentInfoDTO);
        return Result.success(appointmentInfoDTO);
    }

    @Override
    public Result cancelAppointment(Long id, Long userId) {
        CertificateHkMacauBridge hkMacauBridge = hkMacauBridgeMapper.selectById(id);
        if (Objects.isNull(hkMacauBridge)) {
            return Result.failed(SystemError.SYS_411);
        }
        hkMacauBridge.setAcceptStatus(0);
        hkMacauBridgeMapper.updateById(hkMacauBridge);
        return Result.success(hkMacauBridge.getRegisterNumber());
    }
}
